package com.gomyb.oss;

import com.gomyb.oss.config.ConfigProperties;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 * 2019/7/3 21:47
 */
public abstract class FileServiceAbstract implements FileService {

    protected StorageProperties config;

    protected ConfigProperties configProperties;

    @Override
    public void setConfigProperties(ConfigProperties configProperties) {
        if (null == configProperties.getUpload() || configProperties.getUpload().size() == 0) {
            throw new RuntimeException("没有配置云存储");
        }
        if (StringUtils.isNotEmpty(configProperties.getUsing())) {
            StorageProperties storageProperties = configProperties.getUpload().get(configProperties.getUsing());
            if (null != storageProperties) {
                config = storageProperties;
            } else {
                config = configProperties.getUpload().values().iterator().next();
            }
        } else {
            config = configProperties.getUpload().values().iterator().next();
        }
        this.configProperties = configProperties;
    }

    protected final String getFileName(String last) {
        return RandomStringUtils.random(8, true, true) + last;
    }

    protected String getPath() {
        StringBuilder sb = new StringBuilder();
        String path1 = RandomStringUtils.random(1, true, true);
        sb.append(path1).append("/");
        String path2 = RandomStringUtils.random(1, true, true);
        sb.append(path2);
        return sb.toString();
    }

    protected String getFilePath(MultipartFile file) {
        String path = getPath();
        int idx = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");
        String last = file.getOriginalFilename().substring(idx);
        String fileName = getFileName(last);
        return path + "/" + fileName;
    }
}
